﻿using BaseBll;
using BaseWebApi.App_Start;
using BaseWebApi.Common;
using BaseWebApi.Models;
using Common;
using Models;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Http;

namespace BaseWebApi.Controllers
{
    /// <summary>
    /// 资产入库
    /// </summary>
    [ControllerGroup(groupName: "AssetInv", useage: "资产管理-资产入库")]   
    public class AssetInvController : BaseController
    {
        private JWTPlayloadInfo playload;

        /// <summary>
        /// 分页查询
        /// </summary>
        /// <param name="pageIndex">当前页</param>
        /// <param name="pageSize">页尺寸</param>
        /// <param name="assetNo">资产编号</param>
        /// <param name="staffName">使用人员</param>
        /// <param name="deptId">部门id</param>
        /// <param name="buyDate">购买日期</param>
        /// <param name="assetName">资产名称</param>
        /// <param name="assetStatus">资产状态（0：闲置；1：在用）</param>
        /// <returns></returns>
        [HttpGet]
        public HttpResponseMessage GetPageList(int pageIndex, int pageSize, string assetNo = "", string staffName = "", int deptId = 0, string buyDate = "", string assetName = "", int assetStatus = -1)
        {
            string strWhere = "";
            if (!string.IsNullOrEmpty(assetNo))
            {
                strWhere += " and AssetNo like '%" + assetNo + "%'";
            }
            if (!string.IsNullOrEmpty(staffName))
            {
                strWhere += " and StaffName = '" + staffName + "'";
            }
            if (deptId != 0)
            {
                strWhere += " and DeptID = " + deptId;
            }
            if (!string.IsNullOrEmpty(buyDate))
            {
                // 判断是否是日期格式
                // TODO
                strWhere += " and BuyDate = '" + buyDate + "'";
            }
            if (!string.IsNullOrEmpty(assetName))
            {
                strWhere += " and AssetName like '%" + assetName + "%'";
            }
            if (assetStatus != -1)
            {
                strWhere += " and AssetStatus = " + assetStatus;
            }

            DataTable dt = AssetInvBll.Instance.GetPageList(pageSize, pageIndex, strWhere, "BuyDate DESC", out int records);
            int totalPages = PageHelper.GetPageCount(pageSize, records);
            return JsonHelper.SuccessJson(CommonOperation.DataTable2JArray(dt), pageIndex, totalPages, records);
        }

        /// <summary>
        /// 查询（不分页）
        /// </summary>
        /// <param name="assetNo">资产编号</param>
        /// <param name="staffName">使用人员</param>
        /// <param name="deptId">部门id</param>
        /// <param name="typeId">类别id</param>
        /// <param name="buyDate">购买日期</param>
        /// <param name="assetName">资产名称</param>
        /// <param name="assetStatus">资产状态（0：闲置；1：在用）</param>
        /// <returns></returns>
        [HttpGet]
        public HttpResponseMessage GetList(string assetNo = "", string staffName = "", int deptId = 0, int typeId = 0, string buyDate = "", string assetName = "", int assetStatus = -1)
        {
            string strWhere = "";
            if (!string.IsNullOrEmpty(assetNo))
            {
                strWhere += " and AssetNo like '%" + assetNo + "%'";
            }
            if (!string.IsNullOrEmpty(staffName))
            {
                strWhere += " and StaffName = '" + staffName + "'";
            }
            if (deptId != 0)
            {
                strWhere += " and DeptID = " + deptId;
            }
            if (typeId != 0)
            {
                strWhere += " and TypeID = " + typeId;
            }
            if (!string.IsNullOrEmpty(buyDate))
            {
                // 判断是否是日期格式
                // TODO
                strWhere += " and BuyDate = '" + buyDate + "'";
            }
            if (!string.IsNullOrEmpty(assetName))
            {
                strWhere += " and AssetName like '%" + assetName + "%'";
            }
            if (assetStatus != -1)
            {
                strWhere += " and AssetStatus = " + assetStatus;
            }

            List<AssetHead> list = AssetInvBll.Instance.GetList(strWhere);

            return JsonHelper.SuccessJson(JsonHelper.ListToJArray(list));
        }

        /// <summary>
        /// 根据ID获取实体对象
        /// </summary>
        /// <param name="ID">数据表ID</param>
        /// <returns></returns>
        [HttpGet]
        public HttpResponseMessage GetModel(int ID)
        {
            if (ID > 0)
            {
                AssetHead model = AssetInvBll.Instance.GetModelById(ID);
                if (model != null)
                {
                    // 查询文件
                    DataTable dt = UploadBll.Instance.GetFiles(ID, "Asset");
                    model.FileList = CommonOperation.ConvertDataTableToModelList<FileData>(dt);
                    return JsonHelper.SuccessJson(JsonHelper.ModelToJObject(model));
                }
                else
                {
                    return JsonHelper.FailJson("数据不存在");
                }
            }
            else
            {
                return JsonHelper.FailJson("参数错误");
            }
        }

        /// <summary>
        /// 根据主表ID查询所有附属资产
        /// </summary>
        /// <param name="headID">采购申请（主表）ID</param>
        /// <returns></returns>
        [HttpGet]
        public HttpResponseMessage GetAssetBodyList(decimal headID)
        {
            List<AssetBody> list = AssetInvBll.Instance.GetAssetBodyList(headID);

            return JsonHelper.SuccessJson(JsonHelper.ListToJArray(list));
        }

        /// <summary>
        /// 新增资产入库
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public HttpResponseMessage AddAsset([FromBody] AssetHead model)
        {
            playload = (JWTPlayloadInfo)Request.Properties["playload"];
            try
            {
                //验证各字段合法性
                string msg = "";
                bool isOk = AssetInvBll.Instance.VerifyModel(model, ref msg);
                if (isOk)
                {
                    bool res = AssetInvBll.Instance.AddAsset(model);
                    if (res)
                    {
                        // 更新文件信息
                        if (model.FileList != null && model.FileList.Count > 0)
                        {
                            UploadBll.Instance.Update((int)model.ID, model.FileList);
                        }
                        new LogHelper().Info(new LogContent(Utils.GetNextID(), playload.LoginIP, playload.UserName, Constant.SysModule.AssetInv, "新增资产", Constant.ActionEnum.Add, Constant.StatusEnum.Success));
                        return JsonHelper.SuccessJson("新增成功");
                    }
                    else
                    {
                        new LogHelper().Info(new LogContent(Utils.GetNextID(), playload.LoginIP, playload.UserName, Constant.SysModule.AssetInv, "新增资产", Constant.ActionEnum.Add, Constant.StatusEnum.Fail));
                        return JsonHelper.FailJson("新增失败");
                    }
                }
                else
                {
                    return JsonHelper.FailJson(msg);
                }
            }
            catch (Exception ex)
            {
                new LogHelper().Error(new LogContent(Utils.GetNextID(), playload.LoginIP, playload.UserName, Constant.SysModule.AssetInv, "新增资产:" + ex.Message, Constant.ActionEnum.Add, Constant.StatusEnum.Exception), ex);
                throw ex;
            }
        }

        /// <summary>
        /// 修改资产
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public HttpResponseMessage UpdateAsset([FromBody] AssetHead model)
        {
            playload = (JWTPlayloadInfo)Request.Properties["playload"];
            if (model.ID <= 0)
            {
                return JsonHelper.ErrorJson("参数错误");
            }
            try
            {
                bool isExist = AssetInvBll.Instance.IsExist(" and ID=" + model.ID);
                if (!isExist)
                {
                    return JsonHelper.ErrorJson("不存在该数据");
                }
                //验证各字段合法性
                string msg = "";
                bool isOk = AssetInvBll.Instance.VerifyModel(model, ref msg);
                if (isOk)
                {
                    bool res = AssetInvBll.Instance.UpdateAsset(model);
                    if (res)
                    {
                        // 更新文件信息
                        if (model.FileList != null && model.FileList.Count > 0)
                        {
                            UploadBll.Instance.Update((int)model.ID, model.FileList);
                        }
                        new LogHelper().Info(new LogContent(Utils.GetNextID(), playload.LoginIP, playload.UserName, Constant.SysModule.AssetInv, "修改资产", Constant.ActionEnum.Edit, Constant.StatusEnum.Success));
                        return JsonHelper.SuccessJson("修改成功");
                    }
                    else
                    {
                        new LogHelper().Info(new LogContent(Utils.GetNextID(), playload.LoginIP, playload.UserName, Constant.SysModule.AssetInv, "修改资产", Constant.ActionEnum.Edit, Constant.StatusEnum.Fail));
                        return JsonHelper.FailJson("修改失败");
                    }
                }
                else
                {
                    return JsonHelper.FailJson(msg);
                }
            }
            catch (Exception ex)
            {
                new LogHelper().Error(new LogContent(Utils.GetNextID(), playload.LoginIP, playload.UserName, Constant.SysModule.AssetInv, "修改资产:" + ex.Message, Constant.ActionEnum.Edit, Constant.StatusEnum.Exception), ex);
                throw ex;
            }
        }

        /// <summary>
        /// 删除资产（状态为2或3：报废或变卖时才可删除）
        /// </summary>
        /// <param name="id">ID</param>
        /// <returns></returns>
        [HttpPost]
        public HttpResponseMessage DeleteAsset(int id)
        {
            playload = (JWTPlayloadInfo)Request.Properties["playload"];
            try
            {
                if (id <= 0)
                {
                    return JsonHelper.FailJson("参数错误！");
                }
                else
                {
                    // 判断状态（状态为2或3：报废或变卖时才可删除）
                    if (!AssetInvBll.Instance.IsExist(" and ID=" + id + " and AssetStatus in(2,3) "))
                    {
                        return JsonHelper.FailJson("该资产正在使用中，不允许删除！");
                    }
                    else
                    {
                        bool result;
                        // 先删除相关图片
                        DataTable dt = UploadBll.Instance.GetFiles(id, "Asset");
                        if (dt.Rows.Count > 0)
                        {
                            List<FileData> files = CommonOperation.ConvertDataTableToModelList<FileData>(dt);
                            string fid = "";
                            for (int i = 0; i < files.Count; i++)
                            {
                                if (string.IsNullOrEmpty(fid))
                                {
                                    fid = "'" + files[i].RelationId + "'";
                                }
                                else
                                {
                                    fid += ",'" + files[i].RelationId + "'";
                                }
                            }
                            bool res = UploadBll.Instance.DeleteFiles(fid, "Asset", files);
                            if (res)
                            {
                                result = AssetInvBll.Instance.DeleteAsset(id);
                                if (result)
                                {
                                    new LogHelper().Info(new LogContent(Utils.GetNextID(), playload.LoginIP, playload.UserName, Constant.SysModule.AssetInv, "删除资产", Constant.ActionEnum.Delete, Constant.StatusEnum.Success));
                                    return JsonHelper.SuccessJson("删除成功");
                                }
                                else
                                {
                                    new LogHelper().Info(new LogContent(Utils.GetNextID(), playload.LoginIP, playload.UserName, Constant.SysModule.AssetInv, "删除资产", Constant.ActionEnum.Delete, Constant.StatusEnum.Fail));
                                    return JsonHelper.SuccessJson("删除失败");
                                }
                            }
                            else
                            {
                                return JsonHelper.FailJson("删除文件失败");
                            }
                        }
                        else
                        {
                            result = AssetInvBll.Instance.DeleteAsset(id);
                            if (result)
                            {
                                new LogHelper().Info(new LogContent(Utils.GetNextID(), playload.LoginIP, playload.UserName, Constant.SysModule.AssetInv, "删除资产", Constant.ActionEnum.Delete, Constant.StatusEnum.Success));
                                return JsonHelper.SuccessJson("删除成功");
                            }
                            else
                            {
                                new LogHelper().Info(new LogContent(Utils.GetNextID(), playload.LoginIP, playload.UserName, Constant.SysModule.AssetInv, "删除资产", Constant.ActionEnum.Delete, Constant.StatusEnum.Fail));
                                return JsonHelper.SuccessJson("删除失败");
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                new LogHelper().Error(new LogContent(Utils.GetNextID(), playload.LoginIP, playload.UserName, Constant.SysModule.AssetInv, "删除资产:" + ex.Message, Constant.ActionEnum.Delete, Constant.StatusEnum.Exception), ex);
                throw ex;
            }
        }

        #region 上传文件相关

        /// <summary>
        /// 上传图片
        /// </summary>
        /// <returns></returns>
        public HttpResponseMessage UploadPic()
        {
            JWTPlayloadInfo playload = (JWTPlayloadInfo)Request.Properties["playload"];

            List<FileData> list = new List<FileData>();
            HttpFileCollection files = HttpContext.Current.Request.Files;
            FileData model = null;
            foreach (var key in files.AllKeys)
            {
                HttpPostedFile postedFile = files[key];
                if (!string.IsNullOrEmpty(postedFile.FileName))
                {
                    // file.SaveAs(HttpContext.Current.Server.MapPath("~/imgcoll/") + file.FileName);
                    //文件扩展名，不含“.”
                    string fileExt = Utils.GetFileExt(postedFile.FileName);

                    // 文件类型
                    Regex regex = new Regex(@"gif|jpg|jpeg|png|bmp|webp");
                    bool isMatch = regex.IsMatch(fileExt);
                    if (!isMatch)
                    {
                        return JsonHelper.ErrorJson("文件类型不匹配");
                    }

                    model = UploadHelper.SaveFilePic(postedFile, UploadHelper.uploadPath + "images/pc/asset/" + DateTime.Now.ToString("yyyyMMdd"), DateTime.Now.ToString("yyyyMMddHHmmss"));

                    // 文件类型
                    model.FileType = fileExt;

                    // 关联表
                    model.RelationTable = "Asset";

                    if (model != null)
                    {
                        list.Add(model);
                    }
                    else
                    {
                        continue;
                    }
                }
            }
            if (list.Count > 0)
            {
                bool result = UploadBll.Instance.AddList(list);
                if (result)
                {
                    new LogHelper().Info(new LogContent(Utils.GetNextID(), playload.LoginIP, playload.UserName, Constant.SysModule.AssetInv, "上传图片(relationTable:" + model.RelationTable + ")", Constant.ActionEnum.Upload, Constant.StatusEnum.Success));
                    return JsonHelper.SuccessJson(JsonHelper.ListToJArray(list));
                }
                else
                {
                    return JsonHelper.ErrorJson("上传失败，稍后重试");
                }
            }
            else
            {
                return JsonHelper.ErrorJson("没有匹配的文件类型");
            }
        }

        /// <summary>
        /// 根据文件ID删除文件
        /// </summary>
        /// <param name="fileID">文件ID</param>
        /// <returns></returns>
        [HttpPost]
        public HttpResponseMessage DeletePic(string fileID)
        {
            JWTPlayloadInfo playload = (JWTPlayloadInfo)Request.Properties["playload"];
            if (string.IsNullOrEmpty(fileID))
            {
                return JsonHelper.ErrorJson("参数错误");
            }
            FileData model = UploadBll.Instance.GetFileByID(fileID);
            if (model != null)
            {
                bool res = UploadBll.Instance.DeleteFilesByID(fileID, model);
                if (res)
                {
                    new LogHelper().Info(new LogContent(Utils.GetNextID(), playload.LoginIP, playload.UserName, Constant.SysModule.AssetInv, "删除图片(ID:" + fileID + ")", Constant.ActionEnum.Delete, Constant.StatusEnum.Success));
                    return JsonHelper.SuccessJson("删除成功！");
                }
                else
                {
                    return JsonHelper.FailJson("删除失败！");
                }
            }
            else
            {
                return JsonHelper.FailJson("参数错误！");
            }
        }

        #endregion 上传文件相关
    }
}